const Router = require('koa-router')
const home = require('./home')
const user = require('./user')
const common = require('./common')
const msgRobot = require('./msgRobot')
const tool = require('./tool')
const toolPublic = require('./public/tool')
const kmPublic = require('./public/km')
const woshipmPublic = require('./km/woshipm')
const msgPublic = require('./msg/channel')
const topPublic = require('./km/tophub')
const redirectPublic = require('./public/redirect')
const toolEdit = require('./toolEdit')
const resume = require('./resume')
const workbench = require('./workbench')
const infoPublic = require('./public/info')
const systemPublic = require('./public/system')
const share = require('./public/share')
const responseWrapper = require('../middleware/responseWrapper')
const pre = require('../middleware/pre')
const filter = require('../middleware/accessFilter')
const config = require('./config')

// 基础路由
const baseRouter = Router();

// 路由列表
[
  { name: 'index', path: '/', router: home },
  // 公共 API
  { name: 'public tool api', path: '/p/v1/tool-api', router: toolPublic },
  { name: 'public km api', path: '/p/v1/km-api', router: kmPublic },
  { name: 'public km api', path: '/p/v1/km-api/pm', router: woshipmPublic },
  { name: 'public msg api', path: '/p/v1/msg-api', router: msgPublic },
  { name: 'public top api', path: '/p/v1/top-api', router: topPublic },
  { name: 'public info api', path: '/p/v1/info-api', router: infoPublic },
  { name: 'public redirect api', path: '/p/v1/redirect-api', router: redirectPublic },
  { name: 'system api', path: '/p/v1/system-api', router: systemPublic },
  { name: 'share api', path: '/p/v1/share-api', router: share },
  // 标准用户 API
  { name: 'user api', path: '/v1/user-api', router: user },
  // 后台管理 API
  { name: 'msg robot api', path: '/v1/robot-api', router: msgRobot, adminCheck: true },
  { name: 'common api', path: '/v1/common-api', router: common, adminCheck: true },
  { name: 'tool api', path: '/v1/tool-api', router: tool, adminCheck: true },
  { name: 'tool edit api', path: '/v1/tool-api', router: toolEdit, adminCheck: true },
  { name: 'talent api', path: '/v1/talent-api', router: resume, adminCheck: true },
  { name: 'workbench api', path: '/v1/workbench-api', router: workbench, adminCheck: true },
  { name: 'config api', path: '/v1/config-api', router: config, adminCheck: true }
].forEach(subRouter => {
  // API 接口缓存控制
  baseRouter.use((ctx, next) => {
    ctx.response.set('Cache-Control', 'no-cache, no-store, must-revalidate')
    ctx.response.set('Pragma', 'no-cache')
    ctx.response.set('Expires', 0)
    return next()
  })
  // 响应封装中间件加入路由
  baseRouter.use(responseWrapper())
  baseRouter.use(pre())
  // 登陆认证
  if (subRouter.adminCheck) {
    baseRouter.use(subRouter.path, filter.userCheck, filter.adminRequired)
  }
  baseRouter.use(subRouter.path, subRouter.router.routes())
})

module.exports = baseRouter
